package algorithm.LRUCache;

import java.util.*;

class Pair {
    public String name;
    public int val;
    public Pair(String name, int val) {
        this.name = name;
        this.val = val;
    }
}

public class LRUCache {

    public static Deque<Pair> list;
    public static Map<String, Pair> map;
    public static int len;
    public static int cap;

    public LRUCache(int s) {
        list = new LinkedList<>();
        map = new HashMap<>();
        cap = s;
    }

    public static Deque<Pair> getList() {
        return list;
    }
    public static Map<String, Pair> getMap() {
        return map;
    }

    public void put(Pair p) {
        Pair pair = map.get(p.name);
        if (pair != null) {
            list.remove(pair);
        }
        list.add(p);
        len++;
        if (len > cap) {
            map.remove(pair);
            list.poll();
        }
    }

    public Pair get(String n) {
        Pair pair = map.get(n);
        if (pair == null) {
            return null;
        }
        if (list.peekLast().equals(pair)) {
            return pair;
        }
        list.remove(pair);
        list.add(pair);
        return pair;
    }

    public static void main(String[] args) {
        LRUCache cache = new LRUCache(3);
        cache.put(new Pair("A", 1));
        cache.put(new Pair("B", 2));
        cache.put(new Pair("C", 3));
        cache.get("B");
        cache.put(new Pair("D", 4));
        for (Pair i : getList()) {
            System.out.printf("name: %s, val: %s", i.name, i.val);
            System.out.println();
        }
    }
}